{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d6f83b73",
   "metadata": {},
   "source": [
    "## 百度AI开放平台\n",
    "- 本周主要内容：图像识别（认知服务）\n",
    "- 22春_API_人工智能与机器学习_week05"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f677f09",
   "metadata": {},
   "source": [
    "## 通用物体和场景识别\n",
    "- 接口描述\n",
    "> 1.该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "- 请求示例\n",
    "> 2.HTTP 方法：POST\n",
    "- 请求URL\n",
    "> 3.https://gitee.com/link?target=https%3A%2F%2Faip.baidubce.com%2Frest%2F2.0%2Fimage-classify%2Fv2%2Fadvanced_general\n",
    "## 鉴权认证机制(access_token)\n",
    "- 获取Access Token\n",
    "- 获取access_token示例代码:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cf6545b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "78e697be",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.5157ac44db7f48e8641138ee9c75cb3b.315360000.1965135486.282335-25954640', 'expires_in': 2592000, 'session_key': '9mzdCS+Nm76xeeczof9E7TgPkpGtwka/aViu7Mcm7mtHEv5E323vpQRA9NZG/y+jSqbkD0694bWrdaULn1pdR8X/zeDcZQ==', 'access_token': '24.29e421dc379bdd4779df90e0d2b4c435.2592000.1652367486.282335-25954640', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '045fc8ca74d3ee887fd4b5a90e8487a4'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'lTxzlngWxB6jliZmleqMv6xt',\n",
    "    'client_secret':'ZileGeXQNHiz7DRw0CFypXcEjNd4ge17'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2a0b1417",
   "metadata": {},
   "outputs": [],
   "source": [
    "ljt = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fe46184",
   "metadata": {},
   "source": [
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e48e88be",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7c30d79c",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid character in identifier (<ipython-input-6-637d1787256c>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-6-637d1787256c>\"\u001b[1;36m, line \u001b[1;32m3\u001b[0m\n\u001b[1;33m    示例代码：\u001b[0m\n\u001b[1;37m        ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid character in identifier\n"
     ]
    }
   ],
   "source": [
    "# 图像识别 url ： https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]\n",
    "示例代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f4f52e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('[本地文件]', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '[调用鉴权接口获取的token]'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "96470c37",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '天安门广场', 'score': 0.954727, 'root': '', 'baike_info': {}}, {'keyword': '北京天安门', 'score': 0.755137, 'root': '建筑-传统建筑', 'baike_info': {}}, {'keyword': '城楼', 'score': 0.563703, 'root': '建筑-传统建筑', 'baike_info': {}}, {'keyword': '轿车', 'score': 0.226054, 'root': '交通工具-汽车', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%BD%BF%E8%BD%A6/568373', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/ac6eddc451da81cb39db49bf932ec7160924ab189b22', 'description': '轿车(saloon car)是指用于载送人员及其随身物品，且座位布置在两轴之间的汽车。包括驾驶者在内，座位数最多不超过九个。一般轿车强调的是舒适性，以乘员为中心。而且是从经济性考虑出发，选择马力适中、排量小、耗油量小的发动机。在中国内地的行驶证管理方面，轿车特指区别于货车、皮卡、SUV、大巴、中巴的小型汽车，俗称为“小轿车”。在香港，轿车又称私家车。'}}, {'keyword': '居民楼', 'score': 0.030512, 'root': '建筑-其他', 'baike_info': {}}], 'log_id': 1513895234679311971}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('tiananmen.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':ljt,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23373e0e",
   "metadata": {},
   "source": [
    "## 菜品识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "53902ff3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '256', 'has_calorie': True, 'name': '汉堡', 'probability': '0.985449', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B1%89%E5%A0%A1%E5%8C%85/540689', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/810a19d8bc3eb135cfcc2712ab1ea8d3fd1f4414', 'description': '汉堡包是英语Hamburger的音译，是一种发源于德国汉堡的食品，后传入美国，经美国人改良后的美式汉堡风靡全球，是现代西式快餐中的主要食物。最早的汉堡包主要由两片小圆面包夹一块牛肉饼组成，现代汉堡中除夹牛肉饼或其他肉饼(只要是煎或炸的)外，还在圆面包的第二层中涂以黄油、芥末、番茄酱、沙拉酱等，再夹入番茄片、洋葱、蔬菜、酸黄瓜等食物，就可以同时吃到主副食。这种食物食用方便、风味可口、营养全面，现在已经成为畅销世界的方便主食之一。因为汉堡包热量高，含有大量脂肪，所以不适合减肥人群或高血压高血脂人群过量食用。'}}, {'has_calorie': False, 'name': '牛肉煲', 'probability': '0.00686731', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%89%9B%E8%82%89%E7%85%B2/15755789', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/7aec54e736d12f2e3e0e752742c2d5628535686a', 'description': '牛肉煲是由牛腱子肉、牛筒子骨、白萝卜、粉丝、青蒜、香菜、葱、姜等制成。'}}, {'has_calorie': False, 'name': '汉堡套餐', 'probability': '0.00367505', 'baike_info': {}}, {'calorie': '340', 'has_calorie': True, 'name': '小皇堡', 'probability': '0.00244022', 'baike_info': {}}, {'calorie': '298', 'has_calorie': True, 'name': '炸薯条', 'probability': '0.00064704', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%82%B8%E8%96%AF%E6%9D%A1/2810002', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/eaf81a4c510fd9f964c5eddc2b2dd42a2934a4b1', 'description': '炸薯条，源于比利时，炸薯条也是富含丙烯酰胺的食品。是一种由土豆条油炸而成的受大众喜爱的零食。薯香松脆，入口柔酥，回味无穷。'}}], 'log_id': 1513895806248029077}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('hanbao.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "\n",
    "access_token = ljt\n",
    "payload={\n",
    "    'access_token':ljt,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b19a5a45",
   "metadata": {},
   "source": [
    "## 植物识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "09976303",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'name': '月季花', 'score': 0.95491683, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%9C%88%E5%AD%A3%E8%8A%B1/14505544', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/562c11dfa9ec8a139fe24202f903918fa1ecc05c', 'description': '月季花(学名：Rosa chinensis Jacq.)：被称为花中皇后，又称“月月红”，是常绿、半常绿低矮灌木，四季开花﹐一般为红色﹐或粉色、偶有白色和黄色﹐可作为观赏植物，也可作为药用植物，亦称月季。有三个自然变种，现代月季花型多样，有单瓣和重瓣，还有高心卷边等优美花型；其色彩艳丽、丰富，不仅有红、粉、黄、白等单色，还有混色、银边等品种；多数品种有芳香。月季的品种繁多，世界上已有近万种，中国也有千种以上。自然花期4月-9月，花成大型，由内向外，呈发散型，有浓郁香气，可广泛用于园艺栽培和切花。月季的适应性强，耐寒、抗旱，不论地栽、盆栽均可，适用于美化庭院、装点园林、布置花坛、配植花篱、花架，月季栽培容易，可作切花，用于做花束和各种花篮，月季花朵可提取香精，并可入药。也有较好的抗真菌及协同抗耐药真菌活性。红色切花更成为情人间必送的礼物之一，并成为爱情诗歌的主题。中国是月季的原产地之一。月季花荣秀美，姿色多样，四时常开，深受人们的喜爱，中国有52个城市将它选为市花，1985年5月月季被评为中国十大名花第五名。(概述图片参考资料来源：)'}}, {'name': '玫瑰', 'score': 0.6269168, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%8E%AB%E7%91%B0/63206', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b7003af33a87e950352a4e90ad764443fbf2b3111eb2', 'description': '玫瑰(学名：Rosa ssp.英文名称：Rosa)：是蔷薇目，蔷薇科、蔷薇属多种植物和培育花卉的通称名字。直立、蔓延或攀援灌木，多数被有皮刺、针刺或刺毛，稀无刺，有毛、无毛或有腺毛。叶互生；花单生；花托球形、坛形至杯形；花瓣5，稀4，开展，覆瓦状排列，白色、黄色，粉红色至红色；花柱顶生至侧生，外伸，离生或上部合生；花瓣倒卵形，重瓣至半重瓣，花有紫红色、黄色、粉色、白色和各种复色。枝条较为柔弱软垂且多密刺，每年花期只有一次。玫瑰是所有花卉中最著名和最受欢迎的一类。几个世纪以来，玫瑰一直备受推崇。历史证据表明，它们大约在5000年前在中国生长，从那时起它们就一直在历史中发挥作用。无论是古希腊人、罗马人、基督徒、共济会或其他人，玫瑰始终是爱、美和平等的永恒象征。虽然每种颜色表达爱，美和平衡有点不同，但主要的信息仍然是爱。玫瑰有许多不同的含义，这取决于它的颜色。然而，任何玫瑰通常都可以被视为象征：爱、荣誉、信仰、美丽、平衡、热情、智慧、奉献和永恒。玫瑰作为经济作物时，其花朵主要用于食品及提炼香精玫瑰油，玫瑰油应用于化妆品、食品、精细化工等工业。在欧洲诸语言中，蔷薇、玫瑰、月季都是使用同一个词，如英语是rose，德语是Die Rose。玫瑰是英国、美国等14个国家的国花。通俗意义中的“玫瑰”已成为多种蔷薇属植物的通称。且事实上杂交玫瑰也是由蔷薇属下各物种杂交选育所产生。'}}, {'name': '当代月季', 'score': 0.014513709, 'baike_info': {}}, {'name': '月月红', 'score': 0.00410291, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%9C%88%E6%9C%88%E7%BA%A2/3569115', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/0eb30f2442a7d93376c1f0bca74bd11372f00197', 'description': '月月红是中国月季的原变种，也是最初被引种至欧洲参与杂交的中国种源之一。中国月季还有一个原变种叫月月粉，月月粉对杂交月季的育种有着更加重要的意义。花朵颜色顾名思义只有红色一种(后文介绍中有不少是和现代月季的描述混淆了，谨慎阅读)。原产北半球，几乎遍及亚、欧两大洲，中国云南,河南,浙江等地是月季的原产地之一。是治妇女月经不调的常用药物。'}}, {'name': '香水月季', 'score': 0.0037706187, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%A6%99%E6%B0%B4%E6%9C%88%E5%AD%A3/2043098', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/962bd40735fae6cdbd7783870fb30f2443a70f10', 'description': '香水月季(拉丁学名：Rosa odorata (Andr.) Sweet)，蔷薇科常绿或半常绿攀援灌木，枝粗壮，无毛，有粗短钩状皮刺。小叶片椭圆形、卵形或长圆卵形，托叶无毛大部贴生于叶柄，花单生或2-3朵，萼片全缘，披针形，花瓣芳香，倒卵形；果梗短。花期6-9月。稀有种。是优良品种的重要亲本，观赏花卉。'}}], 'log_id': 1513896330021451860}\n"
     ]
    }
   ],
   "source": [
    "## \n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('meigui.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\n",
    "    'access_token':ljt,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8032ecc4",
   "metadata": {},
   "source": [
    "## 作业：尝试使用百度API图像识别其中一个\n",
    "* 做用户需求分析并设计一个最小可行性应用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0f359efa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'score': 0.47238898, 'name': '非果蔬食材'}, {'score': 0.12795055, 'name': '黄瓜'}, {'score': 0.047775798, 'name': '绿豆'}, {'score': 0.04653108, 'name': '西兰花'}, {'score': 0.043489944, 'name': '芦笋'}], 'log_id': 1513897028114100447}\n"
     ]
    }
   ],
   "source": [
    "## \n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('guoshu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\n",
    "    'access_token':ljt,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a460a770",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
